package model

import (
    "encoding/json"
    "fmt"
    "gitee.com/HyoJoo-W/ChatRoom/common/entity"
    "github.com/gomodule/redigo/redis"
)

var (
    MyUserDao *UserDao
)

type UserDao struct {
    pool *redis.Pool
}

// NewUserDao 使用工厂模式,创建UserDao实例
func NewUserDao(pool *redis.Pool) (userDao *UserDao) {
    userDao = &UserDao{
        pool: pool,
    }
    return
}

//根据id查询User
func (this *UserDao) getUserById(conn redis.Conn, id int) (user *entity.User, err error) {
    res, err := redis.String(conn.Do("HGet", "users", id))
    //fmt.Println("test err = ",err)
    if err != nil {
        if err == redis.ErrNil {
            //没有找到id对应的hash
            err = ErrorUserNotExists
        }
        return
    }

    user = &entity.User{}
    //将查到的res反序列化为User实例
    err = json.Unmarshal([]byte(res), user)
    if err != nil {
        fmt.Println("查询到的数据反序列化失败, err = ", err)
        return
    }
    return
}

// Login 登录校验
func (this *UserDao) Login(userId int, userPwd string) (user *entity.User, err error) {
    //从连接池取出一个连接
    conn := this.pool.Get()
    defer conn.Close()

    user, err = this.getUserById(conn, userId)
    if err != nil {
        //fmt.Println("debug err = ", err)
        return
    }

    if userPwd != user.UserPwd {
        err = ErrorUserPwd
        return
    }
    return
}

// Register 注册
func (this *UserDao) Register(user *entity.User) (err error) {
    //从连接池取出一个连接
    conn := this.pool.Get()
    defer conn.Close()

    _, err = this.getUserById(conn, user.UserId)

    if err == nil {
        err = ErrorUserExists
        return
    }

    //序列化,注册
    data, err := json.Marshal(user)
    if err != nil {
        return
    }


    _, err = conn.Do("HSet", "users", user.UserId, string(data))

    if err != nil {
        fmt.Println("[注册]服务器端保存注册用户错误, err = ", err)
        return
    }
    return
}
